package org.exmaple.order;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 多线程环境下如何保持顺序执行
 * 方式一：使用线程的join方法
 */
public class ThreadOrder {

    public static final Logger log = LoggerFactory.getLogger("ThreadOrder");

    public static void main(String[] args)  {

        try{
            test();
        }catch (Exception e){

        }
    }

    /**
     * 方案一：使用线程的join阻塞方法
     * 特点：简单但效率低，牺牲并发性
     * @throws Exception
     */
    public static void test() throws Exception{

        Thread threadA = new Thread() {
            @Override
            public void run() {
                try {
                    Thread.sleep(100);
                }catch (Exception e){

                }
                log.info("threadA结束...");
            }
        };
        Thread threadB = new Thread() {
            @Override
            public void run() {
                try {
                    threadA.join();
                    Thread.sleep(100);
                }catch (Exception e){

                }
                log.info("threadB结束...");
            }
        };
        Thread threadC = new Thread() {
            @Override
            public void run() {
                try {
                    threadB.join();
                    Thread.sleep(100);
                }catch (Exception e){

                }
                log.info("threadC结束...");
            }
        };

        threadA.start();
        threadB.start();
        threadC.start();
    }

    /**
     * 方案二；单线程池
     * 特点‌：天然顺序执行，适合任务队列场景
     */
    public void test2(){
        ExecutorService executor = Executors.newSingleThreadExecutor();
        executor.submit(() -> System.out.print("A"));
        executor.submit(() -> System.out.print("B"));
        executor.submit(() -> System.out.print("C"));
        executor.shutdown();
    }

}
